//
//  CalendarAllFilterAlertView.swift
//  EYEE
//
//  Created by 虫虫乐 on 2018/12/28.
//  Copyright © 2018年 zali. All rights reserved.
//  首页-日历全部筛选弹层view

import UIKit

protocol CalendarAllFilterAlertViewDelegate: NSObjectProtocol {
    //MARK: - 声明代理
    /// 各item点击回调
    ///
    /// - Parameters:
    ///   - data: 点击的数据
    ///   - indexPath: 点击的indexPath
    func cAllFilterSelectedData(_ data:CTopFilterModel, indexPath:IndexPath)
}

extension CalendarAllFilterAlertViewDelegate {
    func cAllFilterSelectedData(_ data:CTopFilterModel, indexPath:IndexPath) {
    }
}

class CalendarAllFilterAlertView: UIView {
    
    //MARK: - 声明属性
    //蒙版view
    lazy var shadowView : UIView = {
        let shadowView = UIView(frame: .zero)
        shadowView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        return shadowView
    }()
    
    //内容view
    lazy var contentsView : UIView = {
        let contentsView = UIView(frame: .zero)
        contentsView.backgroundColor = UIColor.white
        return contentsView
    }()
    
    //地区collection
    lazy var stateCollectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets.init(top: space, left: space, bottom: 0, right: space)
        layout.minimumLineSpacing = 22
        layout.itemSize = CGSize(width: itemW, height: itemH)
        let collectionView = UICollectionView(frame: .zero,
                                              collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate   = self
        collectionView.register(CAllFilterCollectionCell.self, forCellWithReuseIdentifier: CAllFilterCollectionCell.reuseId())
        return collectionView
    }()
    
    //标题
    lazy var titleLB : UILabel = {
        let titleLB = UILabel.makeLabel(font: UIFont.pingfangRegular(size: 16.up), text: "切换地区", textColor: UIColor.getCommonColor(with: .ColorMainType), numberLine: 1, alignment: .left)
        return titleLB
    }()
    
    //关闭按钮
    lazy var closeBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(UIImage(named: "ic_colse"), for: .normal)
        return btn
    }()
    
    var isAdd = true
    var itemColumn = 4
    var space:CGFloat = 12
    var itemW:CGFloat = 80.up
    let itemH:CGFloat = 28.up
    var selectedIndex: Int  = 0
    var dataList:[CTopFilterModel]   = []
    weak var delegate : CalendarAllFilterAlertViewDelegate?
    
    //MARK: - 初始化
    init(frame: CGRect,column:Int = 4) {
        super.init(frame: frame)
        itemColumn = column
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        stateCollectionView.removeObserverBlocks(forKeyPath: "contentSize")
    }
    
    //MARK: - 搭建UI
    func setupUI() {
        backgroundColor = UIColor.clear
        
        //添加
        addSubview(shadowView)
        addSubview(contentsView)
        contentsView.addSubview(titleLB)
        contentsView.addSubview(closeBtn)
        contentsView.addSubview(stateCollectionView)
        
        //布局
        shadowView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        titleLB.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(space)
            make.top.equalToSuperview()
            make.height.equalTo(44.up)
        }
        
        closeBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-space)
            make.centerY.equalTo(titleLB.snp.centerY)
            make.width.height.equalTo(30.up)
        }
        
        stateCollectionView.snp.makeConstraints { (make) in
            make.left.right.width.equalToSuperview()
            make.top.equalTo(titleLB.snp.bottom)
            make.height.equalTo(300.up)
        }
        
        contentsView.snp.makeConstraints { (make) in
            make.left.top.width.equalToSuperview()
            make.bottom.equalTo(stateCollectionView.snp.bottom).offset(60)
        }
    
        //添加事件
//        shadowView.whenTapped { [weak self]  in
//            guard let weakSelf = self else {return}
//            weakSelf.dismiss()
//        }
//
//        closeBtn.addTarget { [weak self] (btn) in
//            guard let weakSelf = self else {return}
//            weakSelf.dismiss()
//        }
        
        self.stateCollectionView.addObserverBlock(forKeyPath: "contentSize") { [weak self] (ll, lll , llll) in
            guard let weakSelf = self else {return}
            let contentSize = weakSelf.stateCollectionView.collectionViewLayout.collectionViewContentSize
            let collectionHeight = contentSize.height > 300.up ? 300.up : contentSize.height
            weakSelf.stateCollectionView.snp.updateConstraints({ (make) in
                make.height.equalTo(collectionHeight)
            })
            weakSelf.contentsView.snp.updateConstraints({ (make) in
                make.bottom.equalTo(weakSelf.stateCollectionView.snp.bottom).offset(60)
            })
            
            let maskPath = UIBezierPath.init(roundedRect: CGRect(x: 0, y: 0, width: screenWidth, height: 44.up + collectionHeight + 60.up), byRoundingCorners: [.bottomLeft,.bottomRight], cornerRadii: CGSize(width: 12, height: 12))
            let maskLayer = CAShapeLayer()
            maskLayer.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 44.up + collectionHeight + 60.up)
            maskLayer.path = maskPath.cgPath
            weakSelf.contentsView.layer.mask = maskLayer
        }
    }
}

extension CalendarAllFilterAlertView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    //MARK: - 事件
    func show() {
//        UIView.show(inTempWindow: { (content) in
//            guard let contentView = content else { return }
//            contentView.addSubview(self)
//            self.snp.makeConstraints { (make) in
//                make.top.equalTo(statusBarAndNavigationBarHeight)
//                make.bottom.left.right.equalToSuperview()
//            }
//        }, rootViewController: nil, windowLevel: UIWindow.Level(rawValue: 0), keyWindow: false)
    }
    
    func dismiss() {
//        UIView.hiddenTempWindow(nil, needDefaultAnimated: true, completedBlock: nil)
    }
    
    //刷新数据
    func refreshDatas(_ list:[CTopFilterModel],selectedIndex:Int = 0) {
        self.dataList = list
        self.selectedIndex = selectedIndex
        self.stateCollectionView.reloadData()
    }
    
    //MARK: - 代理
    //MARK: UICollectionViewDelegate
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CAllFilterCollectionCell.reuseId(), for: indexPath) as! CAllFilterCollectionCell
        if indexPath.row < self.dataList.count {
            let model = self.dataList[indexPath.row]
            cell.cellRefreshDatas(model, isSelected: self.selectedIndex == indexPath.row)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row < self.dataList.count {
            let model = self.dataList[indexPath.row]
            self.selectedIndex = indexPath.row
            collectionView.reloadData()
            self.dismiss()
            guard let cDelegate = self.delegate else {
                return
            }
            cDelegate.cAllFilterSelectedData(model,indexPath: indexPath)
        }
    }
}

class CAllFilterCollectionCell: UICollectionViewCell {
    //MARK: - 声明属性
    lazy var titleBtn : UIButton = {
        let titleBtn = UIButton(type: .custom)
        titleBtn.isUserInteractionEnabled = false
        titleBtn.titleLabel?.numberOfLines = 1
        titleBtn.titleLabel?.textAlignment = .center
        titleBtn.titleLabel?.font = UIFont.pingfangRegular(size: 13.up)
        titleBtn.setTitleColor(UIColor.getCommonColor(with: .ColorMainType), for: .normal)
        titleBtn.setTitleColor(UIColor.getCommonColor(with: .Color707AFCType), for: .selected)
        titleBtn.backgroundColor = UIColor.getCommonColor(with: .ColorE9EAEAType)
        titleBtn.isUserInteractionEnabled = false
        titleBtn.titleLabel?.lineBreakMode = .byTruncatingTail
        return titleBtn
    }()
    
    //MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func reuseId() -> String {
        return NSStringFromClass(CAllFilterCollectionCell.self)
    }
    
    //MARK: - 搭建UI
    func setupUI() {
        contentView.addSubview(titleBtn)
        titleBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        titleBtn.layer.cornerRadius = 2
    }
    
    //MARK: - 刷新数据
    func cellRefreshDatas(_ data:CTopFilterModel, isSelected: Bool) {
        self.titleBtn.setTitle(data.title, for: .normal)
        self.titleBtn.isSelected = isSelected
        self.titleBtn.backgroundColor = isSelected ? UIColor.getCommonColor(with: .ColorD7DAFFType) : UIColor.getCommonColor(with: .ColorE9EAEAType)
    }
}
